package cn.edu.zjicm.wordsnet_d.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.activity.LoginActivity;
import cn.edu.zjicm.wordsnet_d.activity.RegisterActivity;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	private IWXAPI apiWeChat;
	public static Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		apiWeChat = WXAPIFactory.createWXAPI(this, StaticData.APP_ID_WECHAT);
		// apiWeChat.registerApp(StaticDate.APP_ID_WECHAT);
		apiWeChat.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		apiWeChat.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq arg0) {

	}

	@Override
	public void onResp(BaseResp resp) {
		String result = "";

		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			SendAuth.Resp sendResp = null;
			try {
				sendResp = (SendAuth.Resp) resp;
				if (sendResp.state != null && sendResp.state.equals("ZhiMi_English")) {
					if(WXEntryActivity.context == LoginActivity.mLoginActivity)
						LoginActivity.mLoginActivity.updateUserData(sendResp.code);
					else if(WXEntryActivity.context == RegisterActivity.mContext)
						RegisterActivity.mContext.updateUserData(sendResp.code);
					result = "授权成功";
					Toast.makeText(this, result, Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				e.printStackTrace();				
			}
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = "取消授权";
			Toast.makeText(this, result, Toast.LENGTH_LONG).show();
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = "拒绝授权";
			Toast.makeText(this, result, Toast.LENGTH_LONG).show();
			break;
		}
		// Toast.makeText(this, result, Toast.LENGTH_LONG).show();
		finishMyself();
	}

	private void finishMyself() {
		LogUtil.addLog("finish()");
		finish();
	}


}
